package com.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>@filename SSLConfig</p>
 * <p>
 * <p>@description ssl配置类</p>
 * https://blog.csdn.net/u014229347/article/details/93623008
 * @author llspace
 * @version 1.0
 * @since 2019/6/25 10:00
 **/
//@Configuration
public class HttpsConfig {

    @Value("${openHttps}")
    private String openHttps;
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                if ("open".equals(openHttps)) {
                    System.out.println("打开https");
                    SecurityConstraint securityConstraint = new SecurityConstraint();
                    securityConstraint.setUserConstraint("CONFIDENTIAL");
                    SecurityCollection collection = new SecurityCollection();
                    collection.addPattern("/*");
                    securityConstraint.addCollection(collection);
                    context.addConstraint(securityConstraint);
                }
            }
        };
        if ("open".equals(openHttps))
        {
            tomcat.addAdditionalTomcatConnectors(initHttpConnector());
        }
        else
        {
            tomcat.addAdditionalTomcatConnectors();
        }

        return tomcat;
    }

    /*
     * 配置默认的http 8080跳转到https 8443
     */
    private Connector initHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8098);
        connector.setSecure(false);
        connector.setRedirectPort(8888);
        return connector;
    }

}
